package com.rico.gateway.filter;

import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @Description 针对knife4j中的/v2/api-docs接口，返回值自带basePath。
 * 导致gateway路由不做截取的情况下访问出现404，所以加此拦截器针对这个接口的返回值
 * 对象中的basePath的值做去除处理，该filter只对knife4j有效。
 * 为了让该filter有效，注意需要保证该filter的优先级高于其他filter
 * @Author Huang Wenxue
 * @Date 2020/7/20 14:32
 * @Version 1.0
 */
@Component
public class WrapperResponseGlobalFilter implements GlobalFilter, Ordered {

    private final String API_DOCS = "/v2/api-docs";
    private final String API_DOCS_EXT = "/v2/api-docs-ext";

    /**
     * 为了让该filter有效，注意需要保证该filter的优先级高于其他filter
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -2;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        if (uri.endsWith(API_DOCS) || uri.endsWith(API_DOCS_EXT)) {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                        return super.writeWith(fluxBody.map(dataBuffer -> {
                            // probably should reuse buffers
                            byte[] content = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(content);
                            DataBufferUtils.release(dataBuffer);
                            String s = new String(content, Charset.forName("UTF-8")).replaceAll("basePath", "");
                            byte[] contentResponse = s.getBytes();
                            byte[] uppedContent = new String(contentResponse, Charset.forName("UTF-8")).getBytes();
                            return bufferFactory.wrap(uppedContent);
                        }));
                    }
                    return super.writeWith(body);
                }
            };
            return chain.filter(exchange.mutate().response(decoratedResponse).build());
        }
        return chain.filter(exchange);
    }

}
